package is.hi.translator;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class TranslatorActivity extends Activity {
	private Translator translator;
	private TextView statusTextView;
	private EditText wordEditText;
	private TextView translationTextView;
	private Button translateButton;
	private BroadcastReceiver receiver;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		translator = new WebTranslator();

		// Set up user interface
		setContentView(R.layout.main);
		wordEditText = (EditText) findViewById(R.id.WordEditText);
		translationTextView = (TextView) findViewById(R.id.TranslationTextView);
		translateButton = (Button) findViewById(R.id.TranslateButton);
		translateButton.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				StringBuilder translation = new StringBuilder(getString(R.string.translation_string) + " ");
				translation.append(translator.translate(wordEditText.getText().toString()));
				translationTextView.setText(translation);
			}});
		statusTextView = (TextView) findViewById(R.id.status);

		// Set up receiver for network status
		receiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent intent) {
				updateStatus();
			}};
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
		registerReceiver(receiver, filter);
	}

	public void onStart() {
		super.onStart();
		updateStatus();
	}

	private void updateStatus() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		StringBuilder status = new StringBuilder().append(getString(R.string.status_string));
		if (connectivityManager.getActiveNetworkInfo() != null) {
			status.append(" Network");
		} else {
			status.append(" No network");
		}
		statusTextView.setText(status);
	}
}